<script setup lang="ts">
// vue
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useAddressStore } from '@/stores/modules/address'
// type
import type { OrderPreResult } from '../../types/order'
import { ReceiveType } from '@/services/constants'
import {
  orderCreateAPI,
  getMemberOrderRepurchaseByIdAPI,
} from '../../services/order'
import type {
  WhtDatetimePickerEvent,
  WhtDatetimePickerInstance,
} from '@/components/wht-datetime-picker/wht-datetime-picker'
import type { Shop } from '@/types/shop'
// api
import { orderPreAPI, orderPreNowAPI } from '../../services/order'
import { memberAddressListAPI } from '../../services/address'
import { shopGetAddressAPI } from '@/services/shop'
import {
  locationInAreaAPI,
  checkSelectedAddressInAreaAPI,
} from '@/services/location'
import { shopGetBusinessTimeAPI } from '@/services/shop'
// icon
import locationIcon from '@/static/icon/order/location.svg'
// utils
import { useLocation, type LocationData } from '@/utils/location'
// components
import whtDatetimePicker from '@/components/wht-datetime-picker/wht-datetime-picker.vue'
import IconContainer from '@/components/container/icon-container.vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 获取点击立即购买跳转后的参数
const query = defineProps<{
  skuId?: string
  count?: string
  addressId?: string
  orderId?: string
  type?: number
}>()

// 订单备注
const buyerMessage = ref('')
// 收货方式
const receiveType = ref<number>(Number(query.type))
// 时间选择器
const dateTimePickerRef = ref<WhtDatetimePickerInstance>()
// 时间选择器
const dateTime = ref<Date>(new Date())
// 当前时间
const now = new Date()
// 时间选择器快捷选项
const quickOptions = [
  // 现在
  {
    label: '现在',
    value: new Date(),
  },
  {
    label: '三小时后',
    value: new Date(new Date().getTime() + 3 * 60 * 60 * 1000),
  },
  // {
  //   label: '明天',
  //   value: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
  // },
  // {
  //   label: '一个星期后',
  //   value: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000),
  // },
  // {
  //   label: '一个月后',
  //   value: new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000),
  // },
]
// 获取预购买商品数据
const orderPre = ref<OrderPreResult>()
// 自提店地址
const pickUpShop = ref<Shop>()

/**
 * 获取自提店地址
 */
const getPickUpShop = async () => {
  const res = await shopGetAddressAPI()
  pickUpShop.value = res.result
}

/**
 * 计算时间返回 年月日 时分
 */
const formatDateTime = computed(() => {
  if (dateTime.value) {
    const year = dateTime.value.getFullYear()
    const month = (dateTime.value.getMonth() + 1).toString().padStart(2, '0')
    const day = dateTime.value.getDate().toString().padStart(2, '0')
    const hour = dateTime.value.getHours().toString().padStart(2, '0')
    const minute = dateTime.value.getMinutes().toString().padStart(2, '0')
    return `今天 ${hour}:${minute}`
  }
  return ''
})

/**
 * 打开时间选择器
 */
const onOpendatePicker = () => {
  dateTimePickerRef.value?.show(dateTime.value)
}
/**
 * 确认时间选择器
 */
const onConfirmDate = ({ value }: WhtDatetimePickerEvent) => {
  // 每次比较都获取当前时间
  const currentTime = new Date()
  dateTime.value = new Date(currentTime.getTime())

  // 判断是否比当前时间减去30秒还早
  if (value < new Date(Date.now() - 30 * 1000)) {
    // 提示时间不能早于当前时间
    uni.showToast({ icon: 'none', title: '时间不能早于当前时间' })
    dateTime.value = new Date() // 重置为当前时间
    value = new Date(currentTime.getTime()) // 重置为当前时间
    console.log(dateTime.value)
    return
  }

  checkBusinessTime(value)
  // 判断是否在营业时间内
  if (!isBusinessTime.value) {
    uni.showToast({
      icon: 'none',
      title: `请在${timeRange.value[0]} - ${timeRange.value[1]}之间操作`,
      duration: 4000,
    })
    dateTime.value = new Date(currentTime.getTime())
    value = new Date(currentTime.getTime()) // 重置为当前时间
    console.log(dateTime.value)
    return
  }

  // // 判断要比当前时间晚3个小时（恢复注释的功能并使用当前时间）
  // if (value < new Date(currentTime.getTime() + 3 * 60 * 60 * 1000)) {
  //   uni.showToast({ icon: 'none', title: '时间必须晚于当前时间3个小时以上' })
  //   return
  // }

  dateTime.value = value as Date
  console.log(dateTime.value)
}

// 开店时间和关店时间
const timeRange = ref<string[]>([])
// 是否在营业时间中
const isBusinessTime = ref(false)
/**
 * 判断是否在营业时间内
 */
const checkBusinessTime = async (value: any) => {
  const [startTime, endTime] = timeRange.value // 解构获取开始和结束时间

  // 解析开始时间
  const [startHours, startMinutes, startSeconds] = startTime
    .split(':')
    .map(Number)
  // 解析结束时间
  const [endHours, endMinutes, endSeconds] = endTime.split(':').map(Number)

  // 创建今天的开始和结束时间对象
  const start = new Date()
  start.setHours(startHours, startMinutes, startSeconds, 0)

  const end = new Date()
  end.setHours(endHours, endMinutes, endSeconds, 0)

  // 判断选择的时间是否在营业时间内
  if (value >= start && value <= end) {
    isBusinessTime.value = true
    return
  } else {
    isBusinessTime.value = false
  }
  console.log(isBusinessTime.value)
}

/**
 * 获取预购买商品数据
 */
const getMemberOrderPreData = async () => {
  // 是否有立即购买参数
  if (query.count && query.skuId) {
    if (query.addressId === '' || query.addressId === undefined) {
      // 调用立即购买 API
      const res = await orderPreNowAPI({
        count: query.count,
        skuId: query.skuId,
        addressId: query.addressId,
      })
      orderPre.value = res.result
    } else {
      // 调用立即购买 API
      const res = await orderPreNowAPI({
        count: query.count,
        skuId: query.skuId,
      })
      orderPre.value = res.result
      const addressRes = await memberAddressListAPI()
      orderPre.value.userAddresses = addressRes.result
    }
  } else if (query.orderId) {
    // 再次购买
    const res = await getMemberOrderRepurchaseByIdAPI(query.orderId)
    orderPre.value = res.result
  } else {
    // 调用预付订单 API
    const res = await orderPreAPI()
    orderPre.value = res.result
  }
}

// 在 onLoadd 中获取预购买商品数据
onLoad(async () => {
  // 使用 Promise.all 同时获取预购买商品数据和自提店地址
  Promise.all([getMemberOrderPreData(), getPickUpShop()])
  // 获取营业时间
  const res = await shopGetBusinessTimeAPI()
  timeRange.value = res.result.timeRange
})

// 使用地址仓库
const addressStore = useAddressStore()
// 计算出默认收货地址
const selectedAddress = computed(() => {
  if (addressStore.selectedAddress) {
    return addressStore.selectedAddress
  }
  // 判断是否有默认地址
  if (orderPre.value?.userAddresses?.length) {
    const defaultAddress = orderPre.value.userAddresses.find(
      (v) => v.isDefault === 1,
    )
    return defaultAddress
  }
  return null
})

// 提交订单
const onOrderSubmit = async () => {
  // 自提订单
  if (receiveType.value === ReceiveType.PICKUP) {
    console.log('自提订单')

    // 没有时间选择提醒
    if (receiveType.value === ReceiveType.PICKUP && !dateTime.value) {
      uni.showToast({ icon: 'none', title: '请选择时间' })
      return
    }

    await handleGetLocation()

    // 创建订单
    if (isInArea.value) {
      console.log('订单位置判断通过')

      // 发送请求
      const res = await orderCreateAPI({
        buyerMessage: buyerMessage.value,
        goods: orderPre.value!.goods.map((v) => ({
          count: v.count,
          skuId: v.skuId,
        })),
        receiveType: receiveType.value as 0 | 1,
        pickUpTime: new Date(dateTime.value.getTime() + 8 * 60 * 60 * 1000),
        pickUpShopId: pickUpShop.value?.id,
        isInShop: isInShop.value ? 1 : 0,
      })

      console.log('请求请求已发送')

      // 等待300毫秒，关闭当前页面，跳转到订单详情，传递订单id
      setTimeout(() => {
        uni.redirectTo({ url: `/pagesOrder/detail/detail?id=${res.result.id}` })
      }, 300)
    }
  }

  // 配送订单
  if (receiveType.value === ReceiveType.DELIVERY) {
    uni.showToast({ icon: 'none', title: '我是配送订单' })
    // 没有收货地址提醒
    if (
      receiveType.value === ReceiveType.DELIVERY &&
      !selectedAddress.value?.id
    ) {
      return uni.showToast({ icon: 'none', title: '请选择收货地址' })
    }
    // 判断是否在配送范围内
    const result = await checkSelectedAddressInAreaAPI(
      selectedAddress.value!.id,
    )
    const isSelectedAddressInArea = Boolean(result.result)
    if (!isSelectedAddressInArea) {
      return uni.showToast({ icon: 'none', title: '收货地址不在配送范围内' })
    }

    // 创建订单
    const res = await orderCreateAPI({
      addressId: selectedAddress.value!.id,
      buyerMessage: buyerMessage.value,
      goods: orderPre.value!.goods.map((v) => ({
        count: v.count,
        skuId: v.skuId,
      })),
      receiveType: receiveType.value as 0 | 1,
      pickUpTime: dateTime.value,
      pickUpShopId: pickUpShop.value?.id,
    })
    // 等待300毫秒，关闭当前页面，跳转到订单详情，传递订单id
    setTimeout(() => {
      uni.redirectTo({ url: `/pagesOrder/detail/detail?id=${res.result.id}` })
    }, 300)
  }
}

/**
 * 获取当前位置信息
 */
const { getCurrentLocation, getRawLocation } = useLocation()

const locationData = ref<LocationData>()
const isInArea = ref(false)
const handleGetLocation = async () => {
  if (!locationData.value) {
    locationData.value = await getRawLocation()
    const rawLocationResult = await locationInAreaAPI(
      locationData.value.longitude,
      locationData.value.latitude,
    )
    isInArea.value = Boolean(rawLocationResult.result)
  }

  if (isInArea.value) {
    // 结束方法
    return
  }

  // 弹窗提示不在范围内, 并获取当前位置信息, 再次判断是否在范围内
  uni.showModal({
    title: '温馨提示',
    content: '本地定位不在配送范围内，是否手动设置位置？',
    async success(res) {
      if (res.confirm) {
        // 不在范围内, 弹出提示框, 并获取当前位置信息, 再次判断是否在范围内
        locationData.value = await getCurrentLocation()
        const currentLocationResult = await locationInAreaAPI(
          locationData.value.longitude,
          locationData.value.latitude,
        )
        isInArea.value = Boolean(currentLocationResult.result)
        if (!isInArea.value) {
          uni.showModal({
            title: '温馨提示',
            icon: 'fail',
            content: '定位不在配送范围内，无法购买',
            showCancel: false,
          })
        }
      }
    },
  })
}

/**
 * 选择收货地址
 */
const onSelectAddress = () => {
  if (receiveType.value === ReceiveType.PICKUP) {
    return
  }

  uni.navigateTo({
    url: `/pagesMember/address/address?from=order`,
  })
}

/**
 * 是否堂食
 */
const isInShop = ref(true)
// const onSelectType = (e: any) => {
//   isInShop.value = e.detail.value
// }
</script>

<template>
  <scroll-view scroll-y class="viewport">
    <!-- 收货地址 -->
    <view class="shipment" hover-class="none" @click="onSelectAddress">
      <view class="location-icon">
        <IconContainer :icon="locationIcon" size="65rpx"></IconContainer>
      </view>

      <view
        v-if="receiveType === ReceiveType.PICKUP"
        class="address-pickup"
        hover-class="none"
        hover-stop-propagation="false"
      >
        <text>{{ pickUpShop?.name }}</text>
        <br />
        <text> {{ pickUpShop?.address }}</text>
      </view>

      <!-- 外卖配送 -->
      <view
        v-if="receiveType === ReceiveType.DELIVERY"
        hover-class="none"
        url="/pagesMember/address/address?from=order"
        class="address-delivery"
      >
        <view v-if="selectedAddress" class="store-address">
          <view class="user">
            {{ selectedAddress.receiver }} {{ selectedAddress.contact }}
          </view>
          <view class="address">
            {{ selectedAddress.fullLocation }} {{ selectedAddress.address }}
          </view>
        </view>
        <text v-else class="no-address"> 请选择收货地址 </text>
      </view>
      <!-- <receiveRadio v-model="receiveType"></receiveRadio> -->
      <view class="receiveTip">
        {{ receiveType === ReceiveType.DELIVERY ? '外卖配送' : '到店自取' }}
      </view>
    </view>

    <view class="isInShop-Container" v-if="receiveType === ReceiveType.PICKUP">
      <view
        class="item"
        :class="isInShop === true ? 'isSelect' : ''"
        @click="isInShop = true"
      >
        <span class="title">堂食</span>
        <span class="desc">店内食用</span>
      </view>
      <view
        class="item"
        :class="isInShop === false ? 'isSelect' : ''"
        @click="isInShop = false"
      >
        <span class="title">打包</span>
        <span class="desc">打包带走</span>
      </view>
    </view>

    <!-- 自提时间 -->
    <view
      class="pick-up-time"
      v-if="receiveType === ReceiveType.PICKUP && !isInShop"
      @click="onOpendatePicker"
    >
      <text class="text">自提时间</text>
      <text>{{ formatDateTime ? formatDateTime : '请选择时间' }}</text>
    </view>
    <wht-datetime-picker
      ref="dateTimePickerRef"
      v-model="dateTime"
      mode="time"
      title="选择时间"
      @confirm="onConfirmDate"
      :startYear="now.getFullYear()"
      :endYear="now.getFullYear() + 1"
      :quickOptions="quickOptions"
    />

    <!-- 商品信息 -->
    <view class="goods">
      <navigator
        v-for="item in orderPre?.goods"
        :key="item.skuId"
        :url="`/pages/goods/goods?id=${item.id}`"
        class="item"
        hover-class="none"
      >
        <image class="picture" :src="item.picture" />
        <view class="meta">
          <view class="name ellipsis"> {{ item.name }} </view>
          <view class="attrs">{{ item.attrsText }}</view>
          <view class="prices">
            <view class="pay-price symbol">{{ item.payPrice }}</view>
            <view class="price symbol">{{ item.price }}</view>
          </view>
          <view class="count">x{{ item.count }}</view>
        </view>
      </navigator>
    </view>

    <!-- 配送及支付方式 -->
    <view class="related">
      <view class="item">
        <text class="text">订单备注</text>
        <input
          class="input"
          :cursor-spacing="30"
          placeholder="请输入订单备注"
          v-model="buyerMessage"
        />
      </view>
    </view>

    <!-- 支付金额 -->
    <view class="settlement">
      <view class="item">
        <text class="text">商品总价: </text>
        <text class="number symbol">{{
          orderPre?.summary.totalPrice.toFixed(2)
        }}</text>
      </view>
      <view class="item" v-if="receiveType === ReceiveType.DELIVERY">
        <text class="text">运费: </text>
        <text class="number symbol">{{
          orderPre?.summary.postFee.toFixed(2)
        }}</text>
      </view>
    </view>

    <!-- 是否堂食 -->
    <!-- <view class="typeSelect" v-if="receiveType === ReceiveType.PICKUP">
      <view class="item">
        <text class="text">是否堂食: </text>
        <switch
          @change="onSelectType"
          :class="isInShop ? 'checked' : ''"
        ></switch>
      </view>
    </view> -->

    <!-- 吸底工具栏 -->
    <view
      class="toolbar"
      :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
    >
      <view class="total-pay symbol">
        <text class="number">{{
          orderPre?.summary.totalPrice.toFixed(2)
        }}</text>
      </view>
      <view class="submit-button" @tap="onOrderSubmit"> 提交订单 </view>
    </view>
    <!-- 底部占位空盒子 -->
    <view class="toolbar-height"></view>
  </scroll-view>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background-color: #f4f4f4;
}

.symbol::before {
  content: '¥';
  font-size: 80%;
  margin-right: 5rpx;
}

.shipment {
  margin: 20rpx;
  padding: 30rpx 30rpx 30rpx 90rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: #fff;
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .location-icon {
    position: absolute;
    left: 9rpx;
  }

  .receiveTip {
    font-size: 35rpx;
    color: #333;
    padding: 10rpx 20rpx;
    // border: #6fd4f6 solid 5rpx;
    border-radius: 20rpx;
    background-color: rgb(241, 220, 136, 0.8);
    // 文字居中
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .icon {
    font-size: 36rpx;
    color: #333;
    transform: translateY(-50%);
    position: absolute;
    top: 50%;
    right: 20rpx;
  }

  .user {
    color: #333;
    margin-bottom: 5rpx;
  }

  .address-pickup {
    color: #666;
  }

  .address-delivery {
    color: #666;
  }
}

/* 是否堂食 */
.isInShop-Container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: #fff;
  margin: 20rpx;
  padding: 10rpx 0;
  color: #333;

  .item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px 20rpx;
    width: 48%;
    margin: 0 auto;

    &.isSelect {
      border: #6fd4f6 solid 5rpx;
      position: relative; /* 确保伪元素定位的参考 */
      border-radius: 20rpx;

      &::after {
        content: '';
        position: absolute;
        top: -5rpx; /* 调整三角形的位置 */
        right: -5rpx; /* 调整三角形的位置 */
        width: 0;
        height: 0;
        border-width: 40rpx;
        border-style: solid;
        border-color: #6fd4f6 #6fd4f6 transparent transparent; /* 设置边框颜色来形成三角形 */
        border-radius: 10rpx;
      }
    }

    .title {
      font-size: 35rpx;
      color: #333;
    }
    .desc {
      font-size: 26rpx;
      color: #666;
    }
  }
}

.pick-up-time {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 80rpx;
  font-size: 26rpx;
  color: #333;
}

.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    padding: 30rpx 0;
    border-top: 1rpx solid #eee;

    &:first-child {
      border-top: none;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrs {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .prices {
      display: flex;
      align-items: baseline;
      margin-top: 6rpx;
      font-size: 28rpx;

      .pay-price {
        margin-right: 10rpx;
        color: #cf4444;
      }

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }

    .count {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 26rpx;
      color: #444;
    }
  }
}

.related {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .input {
    flex: 1;
    text-align: right;
    margin: 20rpx 0;
    padding-right: 20rpx;
    font-size: 26rpx;
    color: #999;
  }

  .item .text {
    width: 125rpx;
  }
}

/* 结算清单 */
.settlement {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .danger {
    color: #cf4444;
  }
}

/* 类型选择 */
.typeSelect {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .danger {
    color: #cf4444;
  }
}

/* 吸底工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .total-pay {
    font-size: 40rpx;
    color: #cf4444;

    .decimal {
      font-size: 75%;
    }
  }

  .submit-button {
    width: 220rpx;
    text-align: center;
    line-height: 72rpx;
    font-size: 26rpx;
    color: #fff;
    border-radius: 72rpx;
    background-color: #6fd4f6;
  }
}

// 底部占位空盒子
.toolbar-height {
  height: 200rpx;
}
</style>
